<template>
  <div v-if="show" class="modal-overlay" @click.self="handleClose">
    <div class="modal-content">
      <div class="modal-header">
        <h3>实验室用户管理</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="permissions-container">
          <!-- 所有用户窗口 -->
          <div v-if="showAllUsers" class="permission-section">
            <h4>所有用户</h4>
            <div class="search-box">
              <input 
                type="text" 
                v-model="allUsersSearchQuery" 
                placeholder="搜索用户..." 
                class="search-input"
              />
            </div>
            <div v-if="showAllUsers" class="user-list">
              <div 
                v-for="user in filteredUsers" 
                :key="user.id"
                class="user-item"
              >
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-username">{{ user.username }}</div>
                </div>
                <button 
                  class="action-btn" 
                  @click.stop="addUserToCurrentGroup(user.id)"
                  v-if="currentGroupType"
                >
                  添加到{{ {
                    'admin': '管理员',
                    'outbound': '可出库用户列表',
                    'editor': '可编辑用户',
                    'assigner': '可分配权限用户'
                  }[currentGroupType] }}
                </button>
              </div>
              <div v-if="filteredUsers.length === 0" class="empty-list">
                没有用户
              </div>
            </div>
          </div>

          <!-- 管理员列表 - 仅超级管理员可见 -->
          <div class="permission-section" v-if="isAdmin && (!showAllUsers || currentGroupType === 'admin')">
            <h4>
              管理员列表
              <button class="add-btn" @click="setCurrentGroupType('admin')">
                {{ currentGroupType === 'admin' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="user-list">
              <div 
                v-for="user in adminUsers" 
                :key="user.id"
                class="user-item"
              >
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-username">{{ user.username }}</div>
                </div>
                <button 
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'admin')"
                  v-if="isAdmin && showAllUsers"
                >
                  移除
                </button>
              </div>
              <div v-if="adminUsers.length === 0" class="empty-list">
                没有管理员
              </div>
            </div>
          </div>

          <!-- 可出库用户列表 -->
          <div class="permission-section"  v-if="!showAllUsers || currentGroupType === 'outbound'">
            <h4>
              可出库用户列表
              <button class="add-btn" @click="setCurrentGroupType('outbound')">
                {{ currentGroupType === 'outbound' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="user-list">
              <div 
                v-for="user in outboundUsers" 
                :key="user.id"
                class="user-item"
              >
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-username">{{ user.username }}</div>
                </div>
                <button 
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'outbound')"
                  v-if="(isAdmin || isAdvancedLibraryAdmin) && showAllUsers"
                >
                  移除
                </button>
              </div>
              <div v-if="outboundUsers.length === 0" class="empty-list">
                没有高级管理员
              </div>
            </div>
          </div>

          <!-- 可编辑用户列表 -->
          <div class="permission-section" v-if="((isAdmin || isAdvancedLibraryAdmin || isAssignRole) && (!showAllUsers || currentGroupType === 'editor'))">
            <h4>
              可编辑用户列表
              <button class="add-btn" @click="setCurrentGroupType('editor')">
                {{ currentGroupType === 'editor' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="user-list">
              <div 
                v-for="user in editorUsers" 
                :key="user.id"
                class="user-item"
              >
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-username">{{ user.username }}</div>
                </div>
                <button 
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'editor')"
                  v-if="(isAdmin || isAdvancedLibraryAdmin || isEditRole || isAssignRole) && showAllUsers"
                >
                  移除
                </button>
              </div>
              <div v-if="editorUsers.length === 0" class="empty-list">
                没有可编辑用户
              </div>
            </div>
          </div>

          <!-- 可分配权限用户列表 -->
          <div class="permission-section" v-if="((isAdmin || isAdvancedLibraryAdmin) && (!showAllUsers || currentGroupType === 'assigner'))">
            <h4>
              可分配权限用户列表
              <button class="add-btn" @click="setCurrentGroupType('assigner')">
                {{ currentGroupType === 'assigner' && showAllUsers ? '确定' : '添加用户' }}
              </button>
            </h4>
            <div class="user-list">
              <div 
                v-for="user in assignerUsers" 
                :key="user.id"
                class="user-item"
              >
                <div class="user-info">
                  <div class="user-name">{{ user.nickname }}</div>
                  <div class="user-username">{{ user.username }}</div>
                </div>
                <button 
                  class="remove-btn" 
                  @click.stop="removeUserFromGroup(user.id, 'assigner')"
                  v-if="(isAdmin || isAdvancedLibraryAdmin || isAssignRole) && showAllUsers"
                >
                  移除
                </button>
              </div>
              <div v-if="assignerUsers.length === 0" class="empty-list">
                没有可分配权限用户
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed,Ref } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import { ToastService } from '../../utils/toastService';
import { useLabStore } from '../../stores/labStore';
import { User,ResearchGroupUserRsp } from '../../types';

// 定义props
const props = defineProps<{
  show: boolean;
  labId: string;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'role-updated'): void;
}>();

const handleClose = () => {
  emit('close');
};

const store = useLabStore();

// 用户列表相关
const users = ref<User[]>([]);
const adminUsers = ref<User[]>([]);
const outboundUsers = ref<User[]>([]);
const editorUsers = ref<User[]>([]);
const assignerUsers = ref<User[]>([]);

// 选中用户列表
const selectedAdminUsers = ref<string[]>([]);
const selectedoutboundUsers = ref<string[]>([]);
const selectedEditorUsers = ref<string[]>([]);
const selectedAssignerUsers = ref<string[]>([]);

// 状态管理
const isLoading = ref(false);
const allUsersSearchQuery = ref('');
const selectedUserId = ref<string | null>(null);
const showAllUsers = ref(false);
const currentGroupType = ref<string | null>(null);

// 获取当前登录用户信息
const userInfoStr = localStorage.getItem('userInfo');
const currentUser = ref<User | null>(userInfoStr ? JSON.parse(userInfoStr) : null);
const isAdmin = computed(() => currentUser.value?.roleName === '超级管理员');
const isAdvancedLibraryAdmin = computed(() => {
  if (isAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 4
  );
});
const isEditRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 10
  );
});
const isAssignRole = computed(() => {
  if (isAdmin.value || isAdvancedLibraryAdmin.value) return false;
  if (!currentUser.value?.researchRoleInfos || !store.selectedLab?.id) return false;
  return Object.entries(currentUser.value.researchRoleInfos).some(
    ([groupId, roleId]) => groupId === store.selectedLab?.id && roleId === 12
  );
});

// 过滤后的用户列表
const filteredUsers = computed(() => {
  if (!currentGroupType.value) return [];

  // 获取当前权限组（如管理员、可出库用户等）中已选中的用户列表
  const groupMap = {
    admin: selectedAdminUsers,
    outbound: selectedoutboundUsers,
    editor: selectedEditorUsers,
    assigner: selectedAssignerUsers,
  };

  const selectedArray = groupMap[currentGroupType.value as keyof typeof groupMap]?.value || [];

  // 过滤掉已在当前权限组中的用户，并匹配搜索条件
  const filteredUsers = users.value.filter(user => {
    if (!user.nickname) return false;

    const isInCurrentGroup = selectedArray.includes(user.id);
    const matchesSearch = user.nickname.toLowerCase().includes(allUsersSearchQuery.value.toLowerCase()) || 
                         user.username.toLowerCase().includes(allUsersSearchQuery.value.toLowerCase());

    if (isInCurrentGroup) {
      console.log(`用户 ${user.id} (${user.nickname}) 已在当前权限组中，将被过滤掉`);
    }

    return !isInCurrentGroup && matchesSearch;
  });

  console.log('过滤后的用户列表:', filteredUsers.map(user => user.id));
  return filteredUsers;
});

// 监听show变化，当打开模态框时加载用户列表
watch(() => props.show, (newShow) => {
  if (newShow) {
    fetchAllUsers();
    initGroupUsers();
    selectedUserId.value = null;
  }
});

// 获取所有用户列表
const fetchAllUsers = async () => {
  isLoading.value = true;
  try {
    const response = await fetch(
      `${API_CONFIG.BASE_URL}/user/page?pageNo=1&pageSize=10000`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include'
      }
    );

    const result = await response.json();
    
    if (result.code === 0 || result.code === '0') {
      if (result.data && result.data.dataList) {
        users.value = result.data.dataList;
      }
    } else {
      ToastService.error('获取用户列表失败: ' + result.msg);
    }
  } catch (error) {
    ToastService.error('获取用户列表请求失败: ' + error);
  } finally {
    isLoading.value = false;
  }
};

// 获取分组用户
const fetchGroupUsers = async (roleId: number, targetUsers: Ref<User[]>, selectedUsers: Ref<string[]>) => {
  try {
    const url = new URL(`${API_CONFIG.BASE_URL}/research-group/page/group-user`);
    url.searchParams.append('pageNo', `1`);
    url.searchParams.append('pageSize', `10000`);
    url.searchParams.append('roleId', `${roleId}`);
    url.searchParams.append('researchGroupId', props.labId);
    
    const response = await fetch(url, {
      method: 'GET',
      credentials: 'include'
    });
    
    const result = await response.json();
    if (result.code === "0") {
      targetUsers.value = result.data.dataList.map((user: ResearchGroupUserRsp) => ({
        id: user.userId.toString(),
        nickname: user.nickname,
        roleId: user.roleId
      }));
      // 初始化选中用户列表
      selectedUsers.value = targetUsers.value.map(user => user.id);
    } else if (result.code === '0001') {
      emit('close');
    }
  } catch (error) {
    ToastService.error(`获取权限组用户失败 (roleId: ${roleId}): ${error}`);
  }
};

// 初始化不同权限组的用户数据
const initGroupUsers = async () => {
  try {
    await Promise.all([
      fetchGroupUsers(4, adminUsers, selectedAdminUsers),
      fetchGroupUsers(9, outboundUsers, selectedoutboundUsers),
      fetchGroupUsers(10, editorUsers, selectedEditorUsers),
      fetchGroupUsers(12, assignerUsers, selectedAssignerUsers)
    ]);
  } catch (error) {
    ToastService.error('初始化用户数据失败: ' + error);
  }
};

// 从权限组中移除用户
const removeUserFromGroup = (userId: string, type: 'admin' | 'outbound' | 'editor' | 'assigner') => {
  const currentGroupUsers = {
    admin: adminUsers,
    outbound: outboundUsers,
    editor: editorUsers,
    assigner: assignerUsers
  }[type];
  
  // 同时更新选中用户列表
  const selectedUsers = {
    admin: selectedAdminUsers,
    outbound: selectedoutboundUsers,
    editor: selectedEditorUsers,
    assigner: selectedAssignerUsers
  }[type];

  if (!currentGroupUsers?.value || !selectedUsers?.value) {
    ToastService.error(`无法找到 ${type} 用户组`);
    return;
  }

  // 从当前权限组中移除用户
  const userIndex = currentGroupUsers.value.findIndex(u => u.id === userId);
  if (userIndex !== -1) {
    currentGroupUsers.value.splice(userIndex, 1);
  }
  
  // 从选中用户列表中也移除该用户
  const selectedIndex = selectedUsers.value.indexOf(userId);
  if (selectedIndex !== -1) {
    selectedUsers.value.splice(selectedIndex, 1);
  }

  console.log(`用户 ${userId} 已从 ${type} 组中移除`);
};

// 设置当前权限组类型
const setCurrentGroupType = (type: 'admin' | 'outbound' | 'editor' | 'assigner') => {
  if (currentGroupType.value === type && showAllUsers.value) {
    // 如果已经是当前类型且显示中，则提交权限修改并隐藏所有用户窗口
    handleSubmit(type);
    showAllUsers.value = false;
    currentGroupType.value = null;
  } else {
    // 否则显示所有用户窗口，并设置当前类型
    currentGroupType.value = type;
    showAllUsers.value = true;
    // 重置搜索条件
    allUsersSearchQuery.value = '';
    // 如果用户列表为空，加载用户数据
    if (users.value.length === 0) {
      fetchAllUsers();
    }
  }
};

// 提交权限修改
const handleSubmit = async (type: 'admin' |'outbound' | 'editor' | 'assigner') => {
  try {
    if (!props.labId) {
      ToastService.error('实验组ID不能为空');
      return;
    }
    
    const selectedUsers = type === 'admin' ? selectedAdminUsers.value : type === 'outbound' ? selectedoutboundUsers.value : type === 'editor' ? selectedEditorUsers.value : selectedAssignerUsers.value;
    const roleId = type === 'admin' ? 4 : type === 'outbound' ? 9 : type === 'editor' ? 10 : 12;
    
    const response = await fetch(`${API_CONFIG.BASE_URL}/research-group/update-group-user`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        researchGroupId: props.labId,
        userIds: selectedUsers,
        roleId
      })
    });
    
    const result = await response.json();
    if (result.code === "0") {
      ToastService.success('权限修改成功');
      emit('role-updated');
      // 重新获取所有用户列表数据
      await initGroupUsers();
    } else {
      ToastService.error(`修改失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('修改权限失败:', error);
    ToastService.error('修改权限失败，请检查网络连接');
  }
};

// 添加用户到当前权限组
const addUserToCurrentGroup = (userId: string) => {
  if (!currentGroupType.value) return;

  const currentGroupUsers = {
    admin: adminUsers,
    outbound: outboundUsers,
    editor: editorUsers,
    assigner: assignerUsers
  }[currentGroupType.value];

  if (!currentGroupUsers?.value) {
    ToastService.error(`无法找到 ${currentGroupType.value} 用户组`);
    return;
  }

  // 确保用户不在当前权限组中
  const user = users.value.find(u => u.id === userId);
  if (user && !currentGroupUsers.value.some(u => u.id === userId)) {
    currentGroupUsers.value.push(user);
    console.log(`用户 ${userId} 已添加到 ${currentGroupType.value} 组`);
    // 更新选中用户列表以触发过滤逻辑
    const selectedArray = {
      admin: selectedAdminUsers,
      outbound: selectedoutboundUsers,
      editor: selectedEditorUsers,
      assigner: selectedAssignerUsers
    }[currentGroupType.value];
    if (selectedArray) {
      selectedArray.value = [...selectedArray.value, userId];
    }
  }
};

// 组件挂载时加载用户列表
onMounted(() => {
  if (props.show) {
    fetchAllUsers();
    initGroupUsers();
  }
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: auto;
  max-width: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
  flex: 1;
  overflow-y: auto;
  max-height: 60vh;
  width: 100%;
}

.permissions-container {
  display: flex;
  gap: 16px;
  height: 500px;
  width: 100%;
  overflow-x: visible;
  flex-wrap: nowrap;
}

.permission-section {
  flex: 1;
  min-width: 300px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background-color: #f9f9f9;
}

.permission-section h4 {
  margin: 0 0 16px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
}

.user-list {
  max-height: 300px;
  overflow-y: auto;
}

.user-item {
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #e8e8e8;
  transition: all 0.3s;
  background-color: white;
}

.user-item:hover {
  background-color: #f5f5f5;
}

.user-info {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.user-username {
  font-size: 12px;
  color: #666;
}

.user-role {
  font-size: 12px;
  color: #1890ff;
  background-color: #e6f7ff;
  padding: 2px 8px;
  border-radius: 10px;
}

.action-btn, .remove-btn, .add-btn {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.action-btn {
  background-color: #1890ff;
  color: white;
}

.action-btn:hover {
  background-color: #40a9ff;
}

.remove-btn {
  background-color: #ff4d4f;
  color: white;
}

.remove-btn:hover {
  background-color: #ff7875;
}

.add-btn {
  background-color: #52c41a;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
}

.add-btn:hover {
  background-color: #73d13d;
}

.empty-list {
  padding: 20px;
  text-align: center;
  color: #999;
}
</style>